import util from '../util.js';
import pool from './db.js';

// 查询所有模板
export async function getAllTemplates() {
    const [rows] = await pool.query('SELECT * FROM template');
    return rows;
}

// 根据ID查询模板
export async function getTemplateById(id) {
    const [rows] = await pool.query('SELECT * FROM template WHERE id = ?', [id]);
    return rows[0];
}

// 添加模板
export async function addTemplate(template) {
    const { name, detail, package_id } = template;
    const now = util.getDatetime();
    const [result] = await pool.query(
        'INSERT INTO template (name, detail, package_id, create_time, update_time) VALUES (?, ?, ?, ?, ?)',
        [name, detail, package_id, now, now]
    );
    return result.insertId;
}

// 更新模板
export async function updateTemplate(id, template) {
    const { name, detail, package_id } = template;
    const now = util.getDatetime();
    const [result] = await pool.query(
        'UPDATE template SET name = ?, detail = ?, package_id = ?, update_time = ? WHERE id = ?',
        [name, detail, package_id, now, id]
    );
    return result.affectedRows > 0;
}

// 删除模板
export async function deleteTemplate(id) {
    const [result] = await pool.query('DELETE FROM template WHERE id = ?', [id]);
    return result.affectedRows > 0;
}
